<script setup lang="ts">
import { ref, computed } from 'vue'

// 页签列表
const tabs = ref([
  { id: 'dashboard', title: '首页', path: '/test/simple.html', active: true, closable: false },
  { id: 'dashboard2', title: '首页2', path: '/test/simple-2.html', active: false, closable: true }
])

// 当前激活的页签 ID
const activeTabId = ref('dashboard')

// 获取当前激活的标签页
const currentTab = computed(() => {
  return tabs.value.find(tab => tab.id === activeTabId.value) || tabs.value[0];
});

// 切换页签
const switchTab = (tabId: string) => {
  activeTabId.value = tabId
  // 同时更新 tabs 中的 active 状态，保持数据一致性
  tabs.value.forEach(tab => {
    tab.active = tab.id === tabId
  })
}

// 关闭页签
const closeTab = (tabId: string) => {
  // 找到要关闭的页签索引
  const index = tabs.value.findIndex(tab => tab.id === tabId)
  if (index === -1) return
  
  // 检查是否为可关闭的页签
  if (tabs.value[index].closable !== true) return
  
  // 不能关闭唯一的页签
  if (tabs.value.length === 1) {
    alert('不能关闭唯一的页签')
    return
  }
  
  // 如果关闭的是当前激活的页签，需要切换到其他页签
  if (tabId === activeTabId.value) {
    // 优先切换到下一个页签，如果是最后一个则切换到前一个
    const newActiveIndex = index < tabs.value.length - 1 ? index + 1 : index - 1
    switchTab(tabs.value[newActiveIndex].id)
  }
  
  // 移除页签
  tabs.value.splice(index, 1)
}
</script>

<template>
  <div style="width: 100%; height: 100%; border: 1px solid #e4e7ed; display: flex; flex-direction: column;">
    <!-- 页签栏 -->
    <div style="height: 40px; border-bottom: 1px solid #e4e7ed; background-color: #fff; display: flex; align-items: center; padding: 0 10px; flex-shrink: 0;">
      <div v-for="tab in tabs" :key="tab.id" style="padding: 0 15px; height: 100%; display: flex; align-items: center; background-color: #f5f7fa; cursor: pointer; border-bottom: 2px solid transparent;" :class="{ 'active-tab': tab?.active }" @click="switchTab(tab.id)">
        <span>{{ tab.title }}</span>
        <button v-if="tab.closable" @click.stop="closeTab(tab.id)" style="margin-left: 8px; width: 16px; height: 16px; border: none; background-color: transparent; color: #909399; font-size: 14px; cursor: pointer; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.3s ease;">
          &times;
        </button>
      </div>
    </div>
    
    <!-- 内容主体 -->
    <div style="flex: 1; background-color: #fff; padding: 0px; position: relative; overflow: hidden;">
      <div 
        v-for="tab in tabs" 
        :key="tab.id" 
        style="width: 100%; height: 100%; position: absolute; top: 0; left: 0;"
        v-show="tab.id === activeTabId"
      >
        <iframe
          :id="`iframe-${tab.id}`"
          :src="tab.path"
          frameborder="0"
          allowfullscreen
          style="width: 100%; height: 100%; border: none;"
        ></iframe>
      </div>
    </div>
  </div>
</template>

<style scoped>
.active-tab {
  background-color: #fff !important;
  border-bottom-color: #409eff !important;
}
</style>